package com.wtwd.device.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.dao.RolePermissionMapper;
import com.wtwd.device.dao.SysRoleMapper;
import com.wtwd.device.model.entity.SysRole;
import com.wtwd.device.model.vo.RespCodeEntity;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.model.vo.RolePermissionVo;
import com.wtwd.device.service.SysRoleService;
import com.wtwd.device.utils.TreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mjy
 * @date 2021/08/03
 * @description
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<SysRole> getAllSysRoleList() {
        return sysRoleMapper.getAllSysRoleList();
    }

    @Override
    public RespEntity getRolePermission(Long fatherRoleId, Long subRoleId) {
        List<RolePermissionVo> rolePermissionVos = sysRoleMapper.getRolePermission(fatherRoleId,subRoleId);
        if (rolePermissionVos!=null&&rolePermissionVos.size()>0){
            for (RolePermissionVo rolePermissionVo : rolePermissionVos) {
                 if (StringUtils.isBlank(rolePermissionVo.getCheckRole())){
                     rolePermissionVo.setHasPermission(false);
                 }else {
                     rolePermissionVo.setHasPermission(true);
                 }
            }
        }
        return new RespEntity(RespCode.SUCCESS,TreeUtil.createTree(rolePermissionVos));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespCodeEntity addRolePermission(Long roleId, List<Integer> permissionList) {
        //删除原有权限，重新添加
        rolePermissionMapper.deleteRolePermissionByRoleId(roleId);
        Integer rest = rolePermissionMapper.bathAddRolePermission(roleId, permissionList);
        return new RespCodeEntity(rest>0?RespCode.SUCCESS:RespCode.FAILED) ;
    }

    @Override
    public SysRole getSysRoleByRoleId(Long roleId) {
        return sysRoleMapper.getSysRoleByRoleId(roleId);
    }

    @Override
    public List<SysRole> getSysRoleByRoleTypeList(ArrayList<Integer> roleTypeList) {
        return sysRoleMapper.getSysRoleByRoleTypeList(roleTypeList);
    }

    @Override
    public Integer bathAddRoleType(ArrayList<SysRole> bathAddSysRole) {
        return sysRoleMapper.bathAddRoleType(bathAddSysRole);
    }

    @Override
    public SysRole getSysRoleByRoleType(Integer roleType) {
        return sysRoleMapper.getSysRoleByRoleType(roleType);
    }
}
